{% extends "base.html" %}

{% block title %}{% if detail %}编辑{% else %}添加{% endif %} 详情 - 数据管理系统{% endblock %}

{% block breadcrumb %}
<li class="breadcrumb-item"><a href="{{ url_for('list_main') }}">产品列表</a></li>
<li class="breadcrumb-item"><a href="{{ url_for('list_details', product_id=main.id) }}">{{ main.title }}</a></li>
<li class="breadcrumb-item active" aria-current="page">{% if detail %}编辑{% else %}添加{% endif %}详情</li>
{% endblock %}

{% block content %}
<div>
    <form method="post" action="{{ url_for('download_all_images') }}" id="download-all-form">
        <button type="submit" class="btn btn-danger" id="download-btn">批量下载所有未替换的图片</button>
        <span id="countdown" class="ms-2" style="display: none;"></span>
    </form>
</div>
<div class="form-container">
    <h3 class="mb-4">{% if detail %}编辑{% else %}添加{% endif %} 详情</h3>
    <p class="text-muted"><a href="{{ main.url }}" target="_blank">标题: {{ main.title }}</a></p>

    {% if detail %} <!-- 只在编辑时显示自动编号按钮 -->
    <div>
        <a href="{{ url_for('auto_number_details', id=detail.id) }}" class="btn btn-outline-secondary">
            <i class="bi bi-hashtag"></i> 自动编号
        </a>
    </div>
    {% endif %}

    <!-- 图片显示区域 -->
    {% if detail and (detail.image_url or detail.local_image_path) %}
    <div class="mb-3">
        <label class="form-label">当前图片</label>
        <div>
            {% if detail.local_image_path %}
            <img src="{{ url_for('static', filename=detail.local_image_path.replace('static/', '')) }}"
                class="img-thumbnail" style="max-height: 200px;">
            {% elif detail.image_url %}
            <img src="{{ detail.image_url }}" class="img-thumbnail" style="max-height: 200px;">
            {% endif %}
        </div>
    </div>
    {% endif %}

    <form method="POST" enctype="multipart/form-data">
        <!-- 新增隐藏字段传递id -->
        <input type="hidden" name="id" value="{{ detail.id }}">
        <div class="mb-3">
            <label for="description" class="form-label">产品描述</label>
            <input type="text" class="form-control" id="description" name="description"
                value="{{ detail.description if detail else '' }}">
        </div>

        <div class="mb-3">
            <label for="description_en" class="form-label">产品描述（英文）</label>
            <input type="text" class="form-control" id="description_en" name="description_en"
                value="{{ detail.description_en if detail else '' }}">
        </div>
        <div class="mb-3">
            <label for="other_model" class="form-label">对方型号</label>
            <input type="text" class="form-control" id="other_model" name="other_model"
                value="{{ detail.other_model if detail else '' }}" required>
        </div>

        <div class="mb-3">
            <label for="self_model" class="form-label">自用型号</label>
            <input type="text" class="form-control" id="self_model" name="self_model"
                value="{{ detail.self_model if detail else '' }}" required>
        </div>

        <div class="mb-3">
            <label for="price" class="form-label">价格</label>
            <input type="number" step="0.01" class="form-control" id="price" name="price"
                value="{{ detail.price if detail else '' }}" required>
        </div>

        <div class="mb-3">
            <label for="stock" class="form-label">库存</label>
            <input type="number" class="form-control" id="stock" name="stock"
                value="{{ detail.stock if detail else '0' }}">
        </div>

        <div class="mb-3">
            <label for="image_url" class="form-label">图片URL</label>
            <input type="text" class="form-control" id="image_url" name="image_url"
                value="{{ detail.image_url if detail else '' }}">
        </div>

        <div class="mb-3">
            <label for="local_image_path" class="form-label">本地图片地址</label>
            <input type="text" class="form-control" id="local_image_path" name="local_image_path"
                value="{{ detail.local_image_path if detail else '' }}">
        </div>

        <div class="mb-3">
            <label for="image_file" class="form-label">上传图片替换</label>
            <input type="file" class="form-control" id="image_file" name="image_file" accept="image/*">
            <div class="form-text">支持 JPG, PNG, GIF 格式，上传后将覆盖URL图片</div>
        </div>

        <div class="d-flex justify-content-end mt-4">
            <a href="{{ url_for('list_details', product_id=main.id) }}" class="btn btn-outline-secondary me-2">取消</a>
            <button type="submit" class="btn btn-primary">保存</button>
        </div>
    </form>
</div>
<script>
    // 等待DOM完全加载后再执行代码
    document.addEventListener('DOMContentLoaded', function () {
        // 获取表单和按钮元素
        const downloadForm = document.getElementById('download-all-form');
        const downloadBtn = document.getElementById('download-btn');
        const countdownEl = document.getElementById('countdown');

        // 防重复点击的冷却时间（毫秒）
        const COOLDOWN_TIME = 3000; // 3秒

        // 表单提交事件处理
        downloadForm.addEventListener('submit', function (event) {
            // 阻止表单默认提交行为
            event.preventDefault();

            // 禁用按钮，防止重复点击
            downloadBtn.disabled = true;
            downloadBtn.classList.add('disabled'); // 添加视觉禁用样式

            // 显示倒计时元素
            countdownEl.style.display = 'inline';

            // 设置初始倒计时时间
            let remainingTime = COOLDOWN_TIME / 1000; // 转换为秒

            // 更新倒计时显示
            function updateCountdown() {
                countdownEl.textContent = `(${remainingTime}秒后可再次点击)`;
                remainingTime--;

                // 倒计时结束
                if (remainingTime < 0) {
                    clearInterval(countdownTimer); // 清除定时器
                    countdownEl.style.display = 'none'; // 隐藏倒计时
                    downloadBtn.disabled = false; // 启用按钮
                    downloadBtn.classList.remove('disabled'); // 移除视觉禁用样式
                }
            }

            // 立即显示第一次倒计时
            updateCountdown();

            // 设置定时器，每秒更新一次倒计时
            const countdownTimer = setInterval(updateCountdown, 1000);

            // 发送AJAX请求
            fetch(downloadForm.action, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
                .then(response => {
                    // 请求完成后无论成功失败都停止加载状态
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 请求成功处理
                    if (data.success) {
                        alert(`批量下载任务已启动，共处理 ${data.count} 张图片`);
                        // 如果需要自动刷新页面
                        setTimeout(() => {
                            location.reload();
                        }, 1000);
                    } else {
                        alert(data.message || '任务启动失败');
                    }
                })
                .catch(error => {
                    // 错误处理
                    console.error('请求出错:', error);
                    alert('请求失败: ' + error.message);

                    // 出错时立即恢复按钮状态
                    clearInterval(countdownTimer);
                    countdownEl.style.display = 'none';
                    downloadBtn.disabled = false;
                    downloadBtn.classList.remove('disabled');
                })
                .finally(() => {
                    // 无论成功失败都会执行的代码
                    // 注意：我们不在这里恢复按钮状态，因为要保持3秒冷却
                });
        });
    });
</script>
{% endblock %}